package com.core.db;

import com.alibaba.druid.pool.DruidDataSource;
import com.util.ValueUtil;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by lin.wei on 2020-06-09.
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    public static Map<Object, Object> dataSourcesMap = new ConcurrentHashMap<>(10);

    public static Map<String,String> odbcMap = new ConcurrentHashMap(10);

    public static String DEFAULT_DATASOURCE = "defaultDataSource";

    static {
        dataSourcesMap.clear();
        dataSourcesMap.put(DEFAULT_DATASOURCE, SpringUtils.getBean(DEFAULT_DATASOURCE));
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return Dbs.getDbSourceKey();
    }

    public static void setDataSource(String dataSource) {
//        DynamicDataSource.dataSourceKey.set(dataSource);
        Dbs.setDbSourceKey(dataSource);
        DynamicDataSource dynamicDataSource = (DynamicDataSource) SpringUtils.getBean("dataSource");
        dynamicDataSource.afterPropertiesSet();
    }
    public static void setDataSource(String dataSourceKey,Map<String, Object> odbcMap) {
        DruidDataSource druidDataSource = (DruidDataSource) dataSourcesMap.get(dataSourceKey);

        if(druidDataSource == null){
            druidDataSource = new DruidDataSource();
            druidDataSource.setUrl(ValueUtil.toStr(odbcMap.get("dbcurl")));
            //用户
            druidDataSource.setUsername(ValueUtil.toStr(odbcMap.get("dbcuser")));
            //密码
            druidDataSource.setPassword(ValueUtil.toStr(odbcMap.get("dbcpwd")));
            druidDataSource.setMaxActive(50);
            druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(50);
            druidDataSource.setTestOnBorrow(true);
            druidDataSource.setValidationQuery("select 1");

            druidDataSource.setDriverClassName(ValueUtil.toStr(odbcMap.get("dbcdriver")));
            DynamicDataSource.dataSourcesMap.put(dataSourceKey, druidDataSource);

            Dbs.setDbSourceKey(dataSourceKey);
            DynamicDataSource dynamicDataSource = (DynamicDataSource) SpringUtils.getBean("dataSource");
            dynamicDataSource.afterPropertiesSet();
        }else{
            Dbs.setDbSourceKey(dataSourceKey);
        }
    }
    public static String getDataSource() {
        return Dbs.getDbSourceKey();
    }

    public static void clear() {
        Dbs.clear();
    }


//    protected Object determineCurrentLookupKey() {
//        return DynamicDataSourceContextHolder.getDataSourceType();
//    }
}
